<script setup lang="ts">
import { ref, nextTick } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const context = ref()
const canvas = ref()
const apiUrl = 'http://127.0.0.1:8089/PPSignSDK/'
const initUrl = apiUrl + 'InitialDevice?id=2&width=580&height=380'
const uninitUrl = apiUrl + 'UninitialDevice?id=2'
const getInkUrl = apiUrl + 'GetInks'
const clrInkUrl = apiUrl + 'Clear'
const dialogVisible = ref(false)
const isPolling = ref(false)
const fullscreenLoading = ref(false)
const openDialog = () => {
  dialogVisible.value = true
  nextTick(() => {
    canvas.value = document.getElementById('ppCanvas')
    if (canvas.value.getContext) {
      context.value = canvas.value.getContext('2d')
    }
    initDevice()
  })
}

const lastSignatureBase64Data = ref('')
// 初始化签名板
const initDevice = () => {
  fullscreenLoading.value = true
  axios
    .get(initUrl)
    .then((res) => {
      if (res) {
        isPolling.value = true
        getInk()
      }
    })
    .catch((err) => {
      !err.isError &&
        ElMessage({ type: 'error', message: '蒙恬签字板状态异常，请检查设备是否正常连接！' })
    })
    .finally(() => {
      fullscreenLoading.value = false
    })
}

const drawImage = (base64: string) => {
  const dataUrl = 'data:image/png;base64,' + base64

  // 在image中載入圖檔，再畫到canvas呈現
  const img = new Image()

  img.addEventListener(
    'load',
    function () {
      context.value.drawImage(this, 0, 0, canvas.value.width, canvas.value.height)
    },
    false,
  )

  img.src = dataUrl
}
// 轮循获取当前签名base64
const getInk = () => {
  const timeId = setTimeout(function () {
    clearTimeout(timeId)
    if (isPolling.value) {
      axios
        .get(getInkUrl)
        .then((res: any) => {
          const dataInfos = JSON.parse(res.data)
          dataInfos.forEach((value: any) => {
            if (value.EventType === 0) {
              drawImage(value.Image)
              lastSignatureBase64Data.value = value.Image
            }
          })
        })
        .finally(() => {
          if (isPolling.value) getInk()
        })
    }
  }, 100)
}

// 清除签名
const clearQm = () => {
  axios.get(clrInkUrl).then(() => {
    context.value.clearRect(0, 0, canvas.value.width, canvas.value.height)
    lastSignatureBase64Data.value = ''
  })
}
// 关闭签名板
const uninitDevice = () => {
  isPolling.value = false
  axios
    .get(uninitUrl)
    .then((res) => {
      if (res) {
        context.value.clearRect(0, 0, canvas.value.width, canvas.value.height)
        lastSignatureBase64Data.value = ''
      }
    })
    .catch((err) => {
      !err.isError &&
        ElMessage({ type: 'error', message: '蒙恬签字板状态异常，请检查设备是否正常连接！' })
    })
}

const qmtp = ref('')
const confirm = () => {
  uninitDevice()
  qmtp.value = lastSignatureBase64Data.value
    ? 'data:image/png;base64,' + lastSignatureBase64Data.value
    : ''
  dialogVisible.value = false
}

const cancel = () => {
  dialogVisible.value = false
  uninitDevice()
}

defineExpose({ qmtp, openDialog })
</script>

<template>
  <div
    class="jcyqm"
    v-loading.fullscreen.lock="fullscreenLoading"
    element-loading-text="签字板加载中..."
  >
    <img v-if="qmtp" :src="qmtp" ref="jcyqmRef" class="jcyqm-img" />
    <el-dialog v-model="dialogVisible" title="签名" width="640px" :close-on-click-modal="false">
      <canvas id="ppCanvas" width="600" height="375"></canvas>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirm">确 定</el-button>
          <el-button type="primary" @click="clearQm">清 除</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.jcyqm {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  .jcyqm-img {
    max-width: 100%;
    max-height: 100%;
  }
}
</style>
